package com.cw.demo.converter;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cw.demo.api.dto.UserDto;
import com.cw.demo.dao.model.UserDo;
import com.cw.mybatis.starter.converter.BaseConverter;
import com.cw.mybatis.starter.wrapper.BaseWrapper;
import com.cw.starter.common.util.StringUtils;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 用户converter
 *
 * @author chenw
 * @date 2021/7/27
 */
public class UserConverter {
    /**
     * do转dto
     *
     * @param userDo
     * @return
     */
    public static UserDto do2Dto(UserDo userDo) {
        if (userDo == null) {
            return null;
        }
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(BaseConverter.do2Dto(userDo), userDto);
        userDto.setUserName(userDo.getUserName());
        userDto.setSex(userDo.getSex());
        return userDto;
    }

    /**
     * dto转do
     *
     * @param userDto
     * @return
     */
    public static UserDo dto2Do(UserDto userDto) {
        if (userDto == null) {
            return null;
        }
        UserDo userDo = new UserDo();
        BeanUtil.copyProperties(BaseConverter.dto2Do(userDto), userDo);
        userDo.setUserName(userDto.getUserName());
        userDo.setSex(userDto.getSex());
        return userDo;
    }

    /**
     * doList转dtoList
     *
     * @param doList
     * @return
     */
    public static List<UserDto> doList2DtoList(List<UserDo> doList) {
        if (CollectionUtil.isEmpty(doList)) {
            return null;
        }
        return Lists.newArrayList(Iterators.transform(doList.iterator(), UserConverter::do2Dto));
    }

    /**
     * dtoList转doList
     *
     * @param dtoList
     * @return
     */
    public static List<UserDo> dtoList2DoList(List<UserDto> dtoList) {
        if (CollectionUtil.isEmpty(dtoList)) {
            return null;
        }
        return Lists.newArrayList(Iterators.transform(dtoList.iterator(), UserConverter::dto2Do));
    }

    /**
     * 构建查询条件
     *
     * @param userDto
     * @return
     */
    public static LambdaQueryWrapper buildWrapper(UserDto userDto) {
        LambdaQueryWrapper<UserDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        BaseWrapper<UserDo> baseWrapper = new BaseWrapper<>();
        baseWrapper.buildBaseWrapper(lambdaQueryWrapper, userDto);
        if (StringUtils.isNotBlank(userDto.getUserName())) {
            lambdaQueryWrapper.likeRight(UserDo::getUserName, userDto.getUserName());
        }
        return lambdaQueryWrapper;
    }
}
